﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using System.Windows;
using Timer = System.Timers.Timer;

namespace ScreenStudio
{

    #region C++结构体
    [StructLayout(LayoutKind.Sequential)]
    public struct POINT
    {
        public int X;
        public int Y;

        public POINT(int x, int y)
        {
            this.X = x;
            this.Y = y;
        }

        public override string ToString()
        {
            return ("X:" + X + ", Y:" + Y);
        }
    }
    #endregion


    public class MousePosition
    {
        #region 属性

        private bool isRun = false;

        /// <summary>
        /// 采样间隔
        /// </summary>
        public int Interval = 10;


        #endregion
        #region 回调
        /// <summary>
        /// 获取到鼠标位置回调
        /// </summary>
        public event Action<POINT> OnGetMousePosition = (p) => { };
        #endregion

        #region 单例
        private static object lock_obj = new object();
        private static MousePosition instance;
        public static MousePosition Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (lock_obj)
                    {
                        if (instance == null)
                            instance = new MousePosition();
                    }
                }
                return instance;
            }
        }
        #endregion

        #region 构造
        private MousePosition()
        {
        }

        #endregion

        #region 方法
        [DllImport("user32.dll")]
        public static extern bool GetCursorPos(out POINT pt);

        /// <summary>
        /// 获取鼠标位置
        /// </summary>
        /// <returns></returns>
        public POINT GetMousePosition()
        {
            POINT p;
            GetCursorPos(out p);
            return p;
        }

        public async void Start()
        {
            isRun = true;
            await Task.Run(() =>
            {
                while (isRun)
                {
                    Thread.Sleep(Interval);
                    var p = GetMousePosition();
                    OnGetMousePosition.Invoke(p);
                }
            });
        }

        public void Stop()
        {
            isRun = false;
        }
        #endregion


    }
}
